package com.team1.system.blockchain.service;

import com.alibaba.fastjson2.JSON;
import com.team1.common.utils.SecurityUtils;
import com.team1.system.blockchain.domain.Block;
import com.team1.system.blockchain.domain.BlockCache;
import com.team1.system.blockchain.domain.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.team1.system.blockchain.util.CryptoUtil.SHA256;

@Service
public class BlockService {

    @Autowired
    private BlockCache blockCache;

    /**
     * 创建创世区块
     * @return
     */
    public String createGenesisBlock() {
        Block genesisBlock = new Block();
        //设置创世区块高度为1
        genesisBlock.setIndex(1);
        genesisBlock.setBusinessInfo("创世区块|区块链高度为：1");
        genesisBlock.setTimestamp(System.currentTimeMillis());
        genesisBlock.setNonce(1);
        //封装业务数据
        List<Transaction> tsaList = new ArrayList<Transaction>();
        Transaction tsa = new Transaction();
        tsa.setId(1);
        tsaList.add(tsa);
        genesisBlock.setTransactions(tsaList);
        //设置创世区块的hash值
        genesisBlock.setHash(SHA256(""+tsaList+1));
        //添加到已打包保存的业务数据集合中
        blockCache.getPackedTransactions().addAll(tsaList);
        //添加到区块链中
        blockCache.getBlockChain().add(genesisBlock);
        return JSON.toJSONString(genesisBlock);
    }

    /**
     * 创建新区块
     * @param nonce
     * @param previousHash
     * @param hash
     * @param blockTxs
     * @return
     */
    public Block createNewBlock(int nonce, String previousHash, String hash, List<Transaction> blockTxs) {
        Block block = new Block();
        block.setIndex(blockCache.getBlockChain().size() + 1);
        block.setBusinessInfo("IP为"+ SecurityUtils.getLoginUser().getIpaddr() +"的节点挖矿生成的区块|"+
                "区块链高度为："+(blockCache.getLatestBlock().getIndex()+1));
        //时间戳
        block.setTimestamp(System.currentTimeMillis());
        block.setTransactions(blockTxs);
        //工作量证明，计算正确hash值的次数
        block.setNonce(nonce);
        //上一区块的哈希
        block.setPreviousHash(previousHash);
        //当前区块的哈希
        block.setHash(hash);
        if (addBlock(block)) {
            return block;
        }
        return null;
    }

    /**
     * 添加新区块到当前节点的区块链中
     *
     * @param newBlock
     */
    public boolean addBlock(Block newBlock) {
        //先对新区块的合法性进行校验
        if (isValidNewBlock(newBlock, blockCache.getLatestBlock())) {
            blockCache.getBlockChain().add(newBlock);
            // 新区块的业务数据需要加入到已打包的业务数据集合里去
            blockCache.getPackedTransactions().addAll(newBlock.getTransactions());
            return true;
        }
        return false;
    }

    /**
     * 验证新区块是否有效
     *
     * @param newBlock
     * @param previousBlock
     * @return
     */
    public boolean isValidNewBlock(Block newBlock, Block previousBlock) {
        if (!previousBlock.getHash().equals(newBlock.getPreviousHash())) {
            System.out.println("新区块的前一个区块hash验证不通过");
            return false;
        } else {
            // 验证新区块hash值的正确性
            String hash = SHA256(newBlock.getPreviousHash()+newBlock.getTransactions()+newBlock.getNonce());
            if (!hash.equals(newBlock.getHash())) {
                System.out.println("新区块的hash无效: " + hash + " " + newBlock.getHash());
                return false;
            }
        }

        return true;
    }
}

